<template>
  <div class="drug-list-page">
    <div class="drug-list-header">
      <div class="search-row">
        <select v-model="searchField" class="search-select">
          <option value="drugName">药品名称</option>
          <option value="tradeName">商品名</option>
          <option value="manufacturer">生产企业</option>
          <option value="classification">药品分类</option>
        </select>
        <input v-model="search" class="search-input" :placeholder="`请输入${searchFieldName}`" />
        <button class="search-btn" @click="onSearch" :disabled="loading">
          <svg v-if="!loading" viewBox="0 0 20 20" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="2"/><path d="M15.5 15.5L13 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
          <span v-else>...</span>
        </button>
        <button class="reset-btn" @click="onReset" :disabled="loading">重置</button>
      </div>
      <div class="divider"></div>
      <div class="action-row">
        <button class="add-btn" @click="goEdit()" :disabled="loading">+ 新增药品</button>
        <button class="delete-btn" :disabled="!hasSelected || loading" @click="deleteSelected">删除选中</button>
      </div>
    </div>
    <div class="table-scroll-area">
      <table class="drug-table">
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleAll" /></th>
            <th>序号</th>
            <th>药品分类</th>
            <th>医保中文名称</th>
            <th>商品名</th>
            <th>规格</th>
            <th>单位</th>
            <th>支付标准</th>
            <th>生产企业</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <!-- Loading 状态 -->
          <tr v-if="loading">
            <td colspan="11" style="text-align: center; padding: 40px;">
              <span>加载中...</span>
            </td>
          </tr>
          <!-- 无数据状态 -->
          <tr v-else-if="drugs.length === 0">
            <td colspan="11" style="text-align: center; padding: 40px; color: #999;">
              <span>暂无数据</span>
            </td>
          </tr>
          <!-- 正常数据 -->
          <tr v-else v-for="(item, idx) in drugs" :key="item.drugId" :class="{alt: idx % 2 === 1}">
            <td><input type="checkbox" v-model="item.selected" /></td>
            <td>{{ (pagination.pageNum - 1) * pagination.pageSize + idx + 1 }}</td>
            <td>{{ item.classification }}</td>
            <td>{{ item.drugName }}</td>
            <td>{{ item.tradeName }}</td>
            <td>{{ item.specification }}</td>
            <td>{{ item.unit }}</td>
            <td>{{ item.paymentStandard }}</td>
            <td>{{ item.manufacturer }}</td>
            <td>{{ item.remarks }}</td>
            <td>
              <a href="#" @click.prevent="goEdit(item)">编辑</a>
              <span style="margin: 0 4px;">|</span>
              <a href="#" @click.prevent="deleteOne(item)">删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="pagination-bar" v-if="pagination.pageCount > 1">
      <button @click="gotoPage(pagination.pageNum-1)" :disabled="pagination.pageNum===1 || loading">上一页</button>
      <span>第 {{pagination.pageNum}} / {{pagination.pageCount}} 页 (共 {{pagination.total}} 条)</span>
      <button @click="gotoPage(pagination.pageNum+1)" :disabled="pagination.pageNum===pagination.pageCount || loading">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDrugsList, deleteDrug, batchDeleteDrugs } from '@/api/drugs'

const router = useRouter()

// 搜索条件
const search = ref('')
const searchField = ref('drugName')
const selectAll = ref(false)
const loading = ref(false)

// 搜索字段名称映射
const searchFieldNames = {
  drugName: '药品名称',
  tradeName: '商品名',
  manufacturer: '生产企业',
  classification: '药品分类'
}

const searchFieldName = computed(() => searchFieldNames[searchField.value])

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0
})

// 药品列表数据
const drugs = ref([])

// 获取药品列表
const fetchDrugsList = async () => {
  loading.value = true
  try {
    const queryParams = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    
    // 添加搜索条件
    if (search.value.trim()) {
      // 根据选择的字段进行精确搜索
      queryParams[searchField.value] = search.value.trim()
    }
    
    const response = await getDrugsList(queryParams)
    
    if (response.flag) {
      const pageData = response.data
      drugs.value = pageData.records.map(item => ({
        ...item,
        selected: false
      }))
      pagination.total = pageData.total
      pagination.pageCount = pageData.pages || Math.ceil(pageData.total / pagination.pageSize)
    } else {
      ElMessage.error(response.message || '获取药品列表失败')
    }
  } catch (error) {
    console.error('获取药品列表失败:', error)
    ElMessage.error('获取药品列表失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 计算属性
const hasSelected = computed(() => drugs.value.some(item => item.selected))

// 搜索功能
const onSearch = () => {
  pagination.pageNum = 1
  fetchDrugsList()
}

// 重置搜索
const onReset = () => {
  search.value = ''
  searchField.value = 'drugName'
  pagination.pageNum = 1
  fetchDrugsList()
}

// 编辑药品
const goEdit = (item) => {
  if (item) {
    localStorage.setItem('editDrug', JSON.stringify(item))
    router.push(`/medical-info/drugs/edit/${item.drugId}`)
  } else {
    localStorage.removeItem('editDrug')
    router.push('/medical-info/drugs/edit/new')
  }
}

// 删除单个药品
const deleteOne = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除药品"${item.drugName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const response = await deleteDrug(item.drugId)
    
    if (response.flag) {
      ElMessage.success('删除成功')
      fetchDrugsList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除药品失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  } finally {
    loading.value = false
  }
}

// 批量删除药品
const deleteSelected = async () => {
  const selectedItems = drugs.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要删除的药品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedItems.length}个药品吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const ids = selectedItems.map(item => item.drugId)
    const response = await batchDeleteDrugs(ids)
    
    if (response.flag) {
      ElMessage.success('批量删除成功')
      selectAll.value = false
      fetchDrugsList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除药品失败:', error)
      ElMessage.error('批量删除失败: ' + (error.message || '网络错误'))
    }
  } finally {
    loading.value = false
  }
}

// 全选/取消全选
const toggleAll = () => {
  drugs.value.forEach(item => {
    item.selected = selectAll.value
  })
}

// 分页跳转
const gotoPage = (page) => {
  if (page >= 1 && page <= pagination.pageCount) {
    pagination.pageNum = page
    fetchDrugsList()
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchDrugsList()
})
</script>

<style scoped>
.drug-list-page {
  background: none;
  border-radius: 0;
  box-shadow: none;
  padding: 0;
  margin: 0;
  width: 100%;
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.drug-list-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 18px;
  gap: 0;
  background: #f6f8fa;
  padding: 32px 32px 18px 32px;
  border-radius: 8px;
  margin-left: 32px;
  margin-right: 32px;
}

.search-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  width: 100%;
  gap: 12px;
}

.action-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 0;
  padding-left: 0;
}

.search-select {
  height: 38px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 0 12px;
  font-size: 16px;
  background: #fff;
  color: #333;
  min-width: 120px;
}

.search-input {
  flex: 1;
  max-width: 280px;
  height: 38px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 0 16px;
  font-size: 16px;
  background: #fff;
}

.search-btn, .reset-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 38px;
  padding: 0 16px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-width: 80px;
}

.reset-btn {
  background: #909399;
}

.search-btn:disabled, .reset-btn:disabled {
  background: #e0e0e0;
  color: #aaa;
  cursor: not-allowed;
}

.search-btn svg {
  width: 18px;
  height: 18px;
  display: block;
}

.divider {
  width: 100%;
  height: 1px;
  background: #e5e6eb;
  margin: 0 0 18px 0;
}

.add-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 18px;
  font-size: 15px;
  cursor: pointer;
  margin-right: 10px;
  box-shadow: none;
}

.delete-btn {
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 18px;
  font-size: 15px;
  cursor: pointer;
  box-shadow: none;
}

.delete-btn:disabled {
  background: #e0e0e0;
  color: #aaa;
  cursor: not-allowed;
}

.drug-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  margin-top: 0;
  border-radius: 0;
  overflow: hidden;
  box-shadow: none;
}

.drug-table tr.alt {
  background: #f7f9fb;
}

.drug-table tr {
  background: #fff;
}

.drug-table th, .drug-table td {
  border-bottom: 1px solid #ececec;
  padding: 18px 8px;
  text-align: center;
  font-size: 17px;
  color: #222;
  background: transparent;
}

.drug-table th {
  background: #f7f8fa;
  color: #34495e;
  font-weight: 700;
  border-bottom: 2px solid #e5e6eb;
  font-size: 15.5px;
}

.drug-table tbody tr:hover td {
  background: inherit !important;
}

.drug-table tr:last-child td {
  border-bottom: none;
}

.drug-table a {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
  font-size: 14px;
  margin: 0 2px;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background 0.18s;
}

.drug-table a:hover {
  background: #eaf3ff;
  text-decoration: underline;
}

.pagination-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 18px;
  margin: 24px 0 0 0;
}

.pagination-bar button {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 18px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.pagination-bar button:disabled {
  background: #e0e0e0;
  color: #aaa;
  cursor: not-allowed;
}

.table-scroll-area {
  margin-bottom: 12px;
  background: #fff;
  border-radius: 0 0 8px 8px;
}
</style>
